package cn.xw.mq.producer;

import cn.xw.config.RabbitMQConfig;
import cn.xw.entity.MessageSendDTO;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-16 15:01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TestProducer {

    private final RabbitTemplate rabbitTemplate;

    /***
     * 生产者方法
     * @param msg 消息
     */
    public void producerSendMsg(MessageSendDTO msg) {
        //消息转换为JSON格式并转为字节数组
        byte[] bytes = JSONObject.toJSONString(msg).getBytes(StandardCharsets.UTF_8);
        //发送消息
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY, bytes);
        log.info("生产者发送信息完成，已经交由给交换机.....");
    }
}
